<?php
if (! defined ('IN_ZWS')) exit ();

class AuthAction extends Action {
	function _initialize() {
		global $userInfo, $adminUid;
		if (isEmpty($_SESSION['uid']) || isEmpty($_SESSION['ltime'])) $this -> error("请先登录前台", __ROOT__ . '/u/login');
		$M = M('User');
		$userInfo = $M -> join('zws_user_info info ON info.uid = zws_user.id') -> where("zws_user.id=" . $_SESSION['uid']) -> find();
		$adminUid = explode(',', setting('admin_uid'));
		if (empty($userInfo) || empty($userInfo['username']) || $_SESSION['ltime'] < $userInfo['cptime']) {
			unset ($_SESSION ['uid'], $_SESSION ['username'], $_SESSION ['ltime']);
			session ('[destroy]');
			session ('[regenerate]');
			$this -> error("前台登录状态已失效，请重新登录", __ROOT__ . '/u/login');
		}
		$this -> assign('userInfo', $userInfo);
		$this -> assign('siteName', setting('siteName'));
		$this -> assign('siteSubName', setting('siteSubName'));
	}

	function index() {
		header('Location:' . U('login'));
	}

	function login() {
		global $userInfo, $adminUid;
		if (!in_array($_SESSION['uid'], $adminUid)) $this -> error("抱歉，您没有管理权限", __ROOT__ . '/i');
		if (!isEmpty($_COOKIE['atk'])) header('Location:' . __APP__);
		$this -> display();
	}

	function doLogin() {
		global $userInfo;
		if ($userInfo['password'] != md5(md5($this -> _post('password')) . $userInfo['salt'])) $this -> error("抱歉，密码错误");
		setcookie('atk', base64_encode(base64_encode($userInfo['username'] . "\t" . TIMESTAMP . "\t" . $userInfo['cptime'])), TIMESTAMP + 1800, '/');
		$_SESSION['altime'] = TIMESTAMP;
		$this -> success('登录成功', __APP__);
	}

	function logout() {
		if (isEmpty($_COOKIE['atk'])) $this -> error("您尚未登录后台，无需注销", U('auth/login'));
		setcookie('atk', null);
		$this -> success('注销成功', U('auth/login'));
	}
}
